<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\User;
use app\admin\model\insurance\Policy as insuranceModel;
use app\admin\model\insurance\Items;
use app\admin\model\insurance\Refund;
use think\Hook;
use util\XRsa;
use think\Db;
use think\Exception;
use think\exception\ValidateException;

/**
 * 同步保函信息
 */
class Insurance extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

     /**
     * 同步保函申请信息
     *
     * @ApiTitle    (同步保函信息)
     * @ApiSummary  (同步保函信息)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/insurance/apply)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="integer", required=true, description="会员ID")
     * @ApiParams   (name="name", type="string", required=true, description="用户名")
     * @ApiParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
         'code':'1',
         'msg':'返回成功'
        })
     */
    public function apply()
    {
        try {
            $params = $this->request->param();
            trace('接收推送数据：' . json_encode($params), 'insurance');
            
            if (!isset($params['bizContent'])) {
                return json([
                    'message' => '内容不存在',
                    'code' => '99',
                    'success' => false,
                    'result' => ''
                ]);
            }
            
            $config = config('site.zcy');
            if (empty($config['public_key']) || empty($config['private_key'])) {
                throw new Exception('RSA密钥配置不完整');
            }
            
            $public_key = $config['public_key'];
            $private_key = $config['private_key'];
            
            // 初始化RSA
            $rsa = new XRsa($public_key, $private_key);
            
            // 解密数据
            $dataString = $rsa->privateDecrypt($params['bizContent']);
            trace('RSA解密接收推送数据：' . $dataString, 'insurance');
            
            // 验证解密后的数据
            if (empty($dataString)) {
                throw new Exception('解密失败或数据为空');
            }
            
            $data = json_decode($dataString, true);
            if (json_last_error() !== JSON_ERROR_NONE) {
                throw new Exception('JSON解析失败: ' . json_last_error_msg());
            }
            
            if (!isset($data['applyCode'])) {
                throw new Exception('缺少必要的applyCode字段');
            }
            
            // 查找或创建保险记录
            $order = insuranceModel::get(['applyCode' => $data['applyCode']]);
            
            // 开启事务处理，确保数据一致性
            Db::startTrans();
            try {
                if ($order) {
                    // 数据存在则更新
                    $order->allowField(true)->save($data); 
                    $orderId = $order->id;
                } else {
                    // 数据不存在则创建
                    $order = new insuranceModel();
                    $order->allowField(true)->save($data);
                    $orderId = $order->id;
                }
                // 处理保险项目
                if (isset($data['insuranceItems']) && !empty($data['insuranceItems'])) {
                    $itemsResult = Items::add($orderId, $data['insuranceItems']);
                    if (!$itemsResult) {
                        throw new Exception('保险项目保存失败');
                    }
                }
                
                // 提交事务
                Db::commit();
                
                return json([
                    'message' => '成功',
                    'code' => '0000',
                    'success' => true,
                    'result' => ''
                ]);
                
            } catch (Exception $e) {
                // 回滚事务
                Db::rollback();
                throw $e;
            }
            
        } catch (ValidateException $e) {
            trace('验证异常：' . $e->getMessage(), 'error');
            return json([
                'message' => '数据验证失败: ' . $e->getMessage(),
                'code' => '99',
                'success' => false,
                'result' => ''
            ]);
        } catch (Exception $e) {
            trace('系统异常：' . $e->getMessage(), 'error');
            return json([
                'message' => '处理失败: ' . $e->getMessage(),
                'code' => '99',
                'success' => false,
                'result' => ''
            ]);
        } catch (\Throwable $th) {
            trace('严重异常：' . $th->getMessage(), 'error');
            return json([
                'message' => '系统错误',
                'code' => '99',
                'success' => false,
                'result' => ''
            ]);
        }
    }
     /**
     * 同步退保信息
     *
     * @ApiTitle    (同步退保信息)
     * @ApiSummary  (同步退保信息)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/insurance/refund)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="integer", required=true, description="会员ID")
     * @ApiParams   (name="name", type="string", required=true, description="用户名")
     * @ApiParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
         'code':'1',
         'msg':'返回成功'
        })
     */
    public function refund()
    {
        try {
            $params = $this->request->param();
            trace('接收推送数据：' . json_encode($params), 'insurance');
            
            if (!isset($params['bizContent'])) {
                return json([
                    'message' => '内容不存在',
                    'code' => '99',
                    'success' => false,
                    'result' => ''
                ]);
            }
            
            $config = config('site.zcy');
            if (empty($config['public_key']) || empty($config['private_key'])) {
                throw new Exception('RSA密钥配置不完整');
            }
            
            $public_key = $config['public_key'];
            $private_key = $config['private_key'];
            
            // 初始化RSA
            $rsa = new XRsa($public_key, $private_key);
            
            // 解密数据
            $dataString = $rsa->privateDecrypt($params['bizContent']);
            trace('RSA解密接收推送数据：' . $dataString, 'insurance');
            
            // 验证解密后的数据
            if (empty($dataString)) {
                throw new Exception('解密失败或数据为空');
            }
            
            $data = json_decode($dataString, true);
            if (json_last_error() !== JSON_ERROR_NONE) {
                throw new Exception('JSON解析失败: ' . json_last_error_msg());
            }
            
            if (!isset($data['insuranceCode'])) {
                throw new Exception('缺少必要的insuranceCode字段');
            }
            
            // 查找或创建退款记录
            $order = Refund::get(['insuranceCode' => $data['insuranceCode']]);
            
            if ($order) {
                // 数据存在则更新
                $res = $order->allowField(true)->save($data); 
            } else {
                // 数据不存在则创建
                $res = (new Refund())->allowField(true)->save($data); 
            }
            
            return json([
                'message' => '成功',
                'code' => '0000',
                'success' => true,
                'result' => ''
            ]);
            
        } catch (ValidateException $e) {
            trace('验证异常：' . $e->getMessage(), 'error');
            return json([
                'message' => '数据验证失败: ' . $e->getMessage(),
                'code' => '99',
                'success' => false,
                'result' => ''
            ]);
        } catch (Exception $e) {
            trace('系统异常：' . $e->getMessage(), 'error');
            return json([
                'message' => '处理失败: ' . $e->getMessage(),
                'code' => '99',
                'success' => false,
                'result' => ''
            ]);
        }
    }
}
